from typing import List

class Solution:
    def minOperations(self, grid: List[List[int]], x: int) -> int:
        nums = []
        for g in grid:
            nums += g
        nums.sort()
        base = nums[0]
        moves = []
        for n in nums:
            if (n-base) % x != 0:
                return -1
            moves.append((n-base) // x)
        mid = moves[len(moves) // 2]
        # print(mid)
        res = sum([abs(m - mid) for m in moves])
        return int(res)

if __name__ == '__main__':
    s = Solution()
    print(s.minOperations([[931,128],[639,712]], 73))
